﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace miscellaneous
{
    public partial class BindingBug
    {
        readonly Computer currentComputer = new Computer();
        public BindingBug()
        {
            InitializeComponent();
            DataContext = currentComputer;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            currentComputer.Name = "Saturn";
            currentComputer.Mac = "abcdefghijkl";
        }
    }

    // Converts from Nothing of type string to Nothing of type string
    public class NothingToNothingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof (string))
            {
                throw new InvalidOperationException("The target must be of type string");
            }

            // validate input here

            return value;

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }

    public class Computer: INotifyPropertyChanged
    {
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                RaisePropertyChanged("Name");
            }
        }

        private string mac;
        public string Mac
        {
            get { return mac; }
            set
            {
                mac = FormatMacAddress(value);
                RaisePropertyChanged("Mac");
            }
        }

        private static string FormatMacAddress(string s)
        {
            if (s == null || s.Length < 3)
            {
                return s;
            }
            string s1 = "";

            int innerCount = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (innerCount == 2)
                {
                    innerCount = 0;
                    s1 += "-";
                }
                s1 += s[i];
                innerCount++;
            }
            return s1.ToUpper();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
